package DES;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;



public class DES {

    /**
     * 生成密钥
     * @param text
     * @return
     * @throws Exception
     */
    public static SecretKeySpec getSecretKey(String text) throws Exception{
        String originKey = RandUtil.rand(text);
        // 根据给定的字节数组构建一个秘钥
        SecretKeySpec key = new SecretKeySpec(originKey.getBytes(), "DES");
        return key;
    }

    public static String encrypt(String text,SecretKeySpec key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encipherByte = cipher.doFinal(text.getBytes());
        String encode = Base64.encodeBase64String(encipherByte);
        return encode;
    }

    public static String decrypt(String text,SecretKeySpec key) throws Exception {
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        // 3.用加密工具类对象对密文进行解密
        byte[] decode = Base64.decodeBase64(text);
        byte[] decipherByte = cipher.doFinal(decode);
        String decipherText = new String(decipherByte);
        return decipherText;
    }

}


